 package com.example.day09_mybroadcastreceiver;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

 public class MainActivity extends AppCompatActivity {
     private IntentFilter intentFilter;
     private LocalReceiver localReceiver;
     private LocalBroadcastManager localBroadcastManger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        获取实例
        localBroadcastManger = localBroadcastManger.getInstance(this);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("LocalBroadcast");
                // 发送广播
                localBroadcastManger.sendBroadcast(intent);
            }
        });

//        注册广播
        intentFilter = new IntentFilter();
        intentFilter.addAction("LocalBroadcast");
        localReceiver = new LocalReceiver();
        localBroadcastManger.registerReceiver(localReceiver, intentFilter);
    }

     @Override
     protected void onDestroy() {
         super.onDestroy();
         localBroadcastManger.unregisterReceiver(localReceiver);
     }

     private class LocalReceiver extends BroadcastReceiver {
         @Override
         public void onReceive(Context context, Intent intent) {
             Toast.makeText(context, "已接收到本地广播！",Toast.LENGTH_LONG).show();
         }
     }
 }
